// 点对象
function Point(x, y){
	this.x = x;
	this.y = y;
}

// 多边形对象
function Polygon(){
	this.points = [];
	this.strokeStyle = 'blue';
	this.fillStyle = 'white';
}

// 多边形继承形状的属性
Polygon.prototype = new Shape();

Polygon.prototype.collidesWith = function(shape){
	var axes = shape.getAxes();

	if(axes === undefined){
		return polygonCollidesWithCircle(this, shape);
	}else{
		axes.concat(this.getAxes());

		return !this.separationOnAxes(axes, shape);
	}
};

// Projects each point in the polygon onto the specified axis and then returns a projection width the minimum and maximum of those projected points.
// 投影
Polygon.prototype.project = function(axis){
	var scalars = [],
		v = new Vector();

	this.points.forEach(function(point){
		v.x = point.x;
		v.y = point.y;
		scalars.push(v.dotProduct(axis));
	});

	return new Projection(Math.min.apply(Math, scalars), Math.max.apply(Math, scalars));
};

// Returns all of the polygon's axes needed for collision detection testing with SAT
// 获取所有的分离轴
Polygon.prototype.getAxes = function(){
	var v1 = new Vector(),
		v2 = new Vector(),
		axes = [];

	for(var i = 0; i < this.points.length - 1; i++){
		v1.x = this.points[i].x;
		v1.y = this.points[i].y;

		v2.x = this.points[i + 1].x;
		v2.y = this.points[i + 1].y;

		axes.push(v1.edge(v2).normal());
	}

	v1.x = this.points[this.points.length - 1].x;
	v1.y = this.points[this.points.length - 1].y;

	v2.x = this.points[0].x;
	v2.y = this.points[0].y;

	axes.push(v1.edge(v2).normal());

	return axes;
};

// 添加连接点
Polygon.prototype.addPoint = function(x, y){
	this.points.push(new Point(x, y));
};

// 重写了Shape的createPath方法
Polygon.prototype.createPath = function(context){
	if(this.points.length === 0) return;

	context.beginPath();
	context.moveTo(this.points[0].x, this.points[0].y);
	for(var i = 0; i < this.points.length - 1; ++i){
		context.lineTo(this.points[i].x, this.points[i].y);
	}
	context.closePath();
};

// 移动
Polygon.prototype.move = function(dx, dy){
	// for(var i = 0, point; i < this.points.length; i++){
	for(var i = 0, point; i < this.points.length; ++i){
		point = this.points[i];
		point.x += dx;
		point.y += dy;
	}
};